<?php

namespace App\Notifications\Train\TrainOrder;

use App\Facades\Sms;
use App\Models\Train\TrainOrders\TrainOrder;
use App\Models\User\Repositories\Interfaces\UserRepositoryInterface;
use App\Models\User\User;
use App\Trip\Notify\Channel\SmsChannel;
use App\Trip\Notify\Channel\WechatMiniAppChannel;
use App\Trip\Notify\Channel\WechatOfficialChannel;
use App\Trip\Notify\Sms\Messages\Train\TicketFailedNotifyMessage;
use App\Trip\Wechat\Account\WechatOfficialLogin;
use Carbon\Carbon;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class TicketFailedNotify extends Notification
{
    use Queueable;

    private TrainOrder $order;
    private ?User      $user;
    private            $passengers;

    /**
     * Create a new notification instance.
     *
     * @return void
     */

    public function __construct(TrainOrder $order)
    {
        $this->order      = $order;
        $userRepo         = app(UserRepositoryInterface::class);
        $this->user       = $userRepo->getUserByUserId($this->order->getUserId());
        $this->passengers = $this->order->passengers;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [SmsChannel::class, WechatMiniAppChannel::class, WechatOfficialChannel::class];
    }

    function toSms($notifiable)
    {
        try {
            $message = new TicketFailedNotifyMessage($this->order);
            Sms::send($this->order->getMobile(), $message);
        } catch (Exception $e) {
            Log::error("出票失败,短信发送失败:{$e->getMessage()}");
        }
    }


    public function toWechatOfficial($notifiable)
    {
        $user = $this->user?->getOfficialUser();
        if ($user?->isSubscribe() == 1) {
            $mini_user = $this->user->getMiniAppUser();
            $config    = config('weixin.officials')[0]['message']['templates'] ?? [];
            if (empty($config)) {
                Log::info("我发微信 模板消息未找到配置文件,{$this->order->getOrderSn()}");
                return;
            }

            $collect     = collect($config)->where('type', 'train_order_ticket_failed');
            $template_id = $collect->value('template_id');
            $msg         = [
                "touser"      => $user->getOpenId(),
                "template_id" => $template_id,
                "miniprogram" => [
                    "appid"    => $mini_user->getAppId(),
                    "pagepath" => "pages/order/order",
                ],
                "topcolor"    => "#FF0000",
                "data"        => [
                    "first"    => [
                        "value" => __("您好，您预订的火车票购票失败"),
                        "color" => "#173177",
                    ],
                    'keyword1' => [
                        'value' => $this->order->getOrderSn(),
                    ],
                    'keyword2' => [
                        'value' => Str::limit(collect($this->passengers)->map(fn($passenger) => $passenger['truename'])->implode(','), 80),
                    ],
                    'keyword3' => [
                        'value' => Carbon::parse($this->order->getTrainDate())->format("m-".__('月')."d-".__('日')),// 月日
                    ],
                    'keyword4' => [
                        'value' => $this->order->getTrainCode(),
                    ],
                    'keyword5' => [
                        'value' => __($this->order->getSeatName()), // 坐席
                    ],
                    'remark'   => [
                        'value' => '请登录小程序中查看详情，给您带来的不便请谅解。',
                    ],
                ],
            ];

            if (empty($msg)) {
                return;
            }


            $w            = new WechatOfficialLogin();
            $official_app = $w->application();
            $client       = $official_app->getClient();
            $content      = $client->postJson('/cgi-bin/message/template/send', $msg);
            Log::info("微信模板消息:".$content->getContent()."-{{$this->order->getOrderSn()}}");
        } else {
            Log::info("我发微信模板消息未关注公众号,{$this->order->getOrderSn()}");
        }
    }

}
